package com.yuanlang.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * des加密工具
 * @author c_shilei-039
 *
 */
public class DesUtil {
	public static String defKey = "!%YLQBHY";
	String key;

	public DesUtil() {
	}

	public DesUtil(String str) {
		setKey(str); // 生成密匙
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	/**
	 * 加密算法20150525
	 * 
	 * @param source
	 * @param rawKeyData
	 * @return
	 * @throws GeneralSecurityException
	 * @throws UnsupportedEncodingException
	 */
	public byte[] desEncrypt(byte[] source) throws GeneralSecurityException,
			UnsupportedEncodingException {
		// 处理密钥
		SecretKeySpec skey = new SecretKeySpec(key.getBytes("UTF-8"), "DES");
		// 加密
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, skey);
		return cipher.doFinal(source);
	}

	/**
	 * 加密 String 明文输入 ,String 密文输出
	 */
	public String encryptStr(String strMing) {
		byte[] byteMi = null;
		byte[] byteMing = null;
		String strMi = "";
		BASE64Encoder base64en = new BASE64Encoder();
		try {
			byteMing = strMing.getBytes("UTF-8");
			byteMi = this.desEncrypt(byteMing);
			strMi = base64en.encode(byteMi);
			strMi = URLEncoder.encode(strMi);
		} catch (Exception e) {
			throw new RuntimeException(
					"Error initializing SqlMap class. Cause: " + e);
		} finally {
			base64en = null;
			byteMing = null;
			byteMi = null;
		}
		return strMi;
	}

	public static void main(String[] args) throws Exception {
		DesUtil des = new DesUtil(defKey);
		String idNo = "110101198001010037";
		String channel = "YLQBHY";
		String url = "https://msbcdsit.ecpic.com.cn/mobilemsb/product/purchaseListOnOtherChannelPage?" 
				+"idNo="+des.encryptStr(idNo)
				+"&channel="+channel;
		System.out.println(url);
		//https://msbcdsit.ecpic.com.cn/mobilemsb/product/purchaseListOnOtherChannelPage?purchaseListOnOtherChannelPage?idNo=SUw0NKd18T%2Bju54qgCrenTbcoqk5hkXl&channel=YLQBHY

	}
}
